package com.vma.offer.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.vma.offer.vo.CartItemVo;
import com.vma.offer.vo.CartVo;
import com.vma.offer.vo.SpecVo;
import com.vma.shoes.bizModel.model.*;

import java.util.*;

/**
 * Created by chenzui on 2017/4/11.
 */
public class CartService {
    public static void delItems(Integer userId,String ids){
        String[] idArr = ids.split(",");
        for (String id:Arrays.asList(idArr)) {
            CartOffer.dao.findFirst("SELECT * FROM cart_offer WHERE offer_id = ? AND user_id = ? AND status = 1",id,userId).setStatus("0").update();
        }
    }

    public static void addItem(CartItemVo cartItemVo){
        int userId = cartItemVo.getUserId();
        int offerId = cartItemVo.getOfferId();
        CartOffer cart = new CartOffer().setOfferId(offerId).setStatus("1").setUserId(userId);
        cart.save();
        for (SpecVo spec:cartItemVo.getSpecs()) {
            new CartItem().setCartOfferId(cart.getId()).setColorId(spec.getColor()).setLengthId(spec.getLength())
                    .setStatus("1").setItemNumber(spec.getNumber()).save();
        }
    }

    /**
     * 修改购物车中的某个商品信息
     * @param cartItemVo
     */
    public static void update(CartItemVo cartItemVo){
        int userId = cartItemVo.getUserId();
        int offerId = cartItemVo.getOfferId();
        CartOffer cart = CartOffer.dao.findFirst("SELECT * FROM cart_offer WHERE user_id = ? AND offer_id = ? AND status = 1",userId,offerId);
        if(cartItemVo.getSpecs() == null || cartItemVo.getSpecs().size() == 0){
            cart.setStatus("0").update();
        }else {
            List<CartItem> oldItems = CartItem.dao.find("SELECT * FROM cart_item WHERE cart_offer_id = ? AND status = 1",cart.getId());
            for(CartItem oit : oldItems){
                oit.setStatus("0").update();
            }
            for (SpecVo spec:cartItemVo.getSpecs()) {
//                if (spec.getId() != 0){
//                    if(spec.getNumber() != 0){
//                        CartItem.dao.findById(spec.getId()).setItemNumber(spec.getNumber()).update();
//                    }else {
//                        CartItem.dao.findById(spec.getId()).setStatus("0").update();
//                    }
//                }else {
                new CartItem().setCartOfferId(cart.getId()).setStatus("1").setColorId(spec.getColor()).setLengthId(spec.getLength()).setItemNumber(spec.getNumber()).save();
//                }
            }
        }

    }

    /**
     * 初始化购物车单项，修改进货车单项时使用
     * @param offerId,userId
     */
    public static Offer initItemData(Integer offerId, Integer userId){
        Offer offer = Offer.dao.findById(offerId);

        OfferImg img = OfferImg.dao.findFirst("select url from offer_img where offer_spec_id = ?",offerId);

        offer.put("imgUrl",img.getUrl());

        List<SpecItem> offerColors = SpecItem.dao.find("SELECT si.id,si.spec_value FROM offer_2_group o2g,offer_group_2_spec o2g2s,spec_item si " +
                "WHERE o2g.id = o2g2s.offer_group_id and o2g.offer_id = ? " +
                "and si.id = o2g2s.spec_id and si.spec_group_id = 1",offerId);

        List<SpecItem> offerLengths = SpecItem.dao.find("SELECT si.id,si.spec_value FROM offer_2_group o2g,offer_group_2_spec o2g2s,spec_item si " +
                "WHERE o2g.id = o2g2s.offer_group_id and o2g.offer_id = ? " +
                "and si.id = o2g2s.spec_id and si.spec_group_id = 2",offerId);

        offer.put("offerColors",offerColors);

        offer.put("offerLengths",offerLengths);

        //查询已选择的规格
        List<Record> items = Db.find("SELECT " +
                "  ci.id," +
                "  ci.color_id," +
                "  ci.length_id," +
                "  si.spec_value color," +
                "  si2.spec_value length," +
                "  ci.item_number " +
                "FROM cart_offer co,cart_item ci, spec_item si, spec_item si2 " +
                "WHERE co.offer_id = ? AND co.user_id = ? AND ci.status = 1 " +
                "AND co.status = 1 AND ci.cart_offer_id = co.id AND ci.color_id = si.id AND ci.length_id = si2.id",offerId,userId);
        offer.put("choose",items);

        offer.put("price",getCurrentPrice(offer.getId(),offer.getInPrice(),offer.getOutPrice()));
        return offer;
    }

    public static CartVo qryCartItems(Integer userId){
        CartVo cart = new CartVo();
        cart.setItems(new ArrayList<CartItemVo>());
        List<Record> offers = Db.find("SELECT o.*,co.id cart_offer_id FROM offer o,cart_offer co WHERE co.status = 1 and o.id = co.offer_id " +
                "AND co.user_id = ?",userId);

        for (Record offer:offers) {
            Integer cartOfferId = offer.getInt("cart_offer_id");
            List<CartItem> items = CartItem.dao.find("SELECT * FROM cart_item WHERE cart_offer_id = ? AND status = 1",cartOfferId);
            CartItemVo item = new CartItemVo();
            Integer offerId = offer.getInt("id");
            item.setOfferId(offerId);
            item.setOfferName(offer.getStr("offer_name"));
            item.setPrice(getCurrentPrice(offerId,offer.getFloat("in_price"),offer.getFloat("out_price")));
            item.setUserId(userId);
            item.setImgURL(getImgUrl(offerId));
            List<SpecVo> specs = new ArrayList<SpecVo>();
            for (CartItem ci:items) {
                SpecVo sv = new SpecVo();
                sv.setColor(ci.getColorId());
                sv.setColorDesc(SpecItem.dao.findById(ci.getColorId()).getSpecValue());
                sv.setLengthDesc(SpecItem.dao.findById(ci.getLengthId()).getSpecValue());
                sv.setLength(ci.getLengthId());
                sv.setNumber(ci.getItemNumber());
                specs.add(sv);
            }
            //查询当前的售价

            item.setSpecs(specs);
            cart.getItems().add(item);
        }
        return cart;
    }


    private static Float getCurrentPrice(Integer offerId,Float inPrice,Float outPrice){
        Float price = 0.0F;
        List<Offer2Market> list = Offer2Market.dao.find("SELECT * FROM offer_2_market WHERE offer_id = ? AND status = 1",offerId);
        if(list == null || list.size() == 0){
            price = inPrice;
        }else {
            price = outPrice;
        }
        return price;
    }

    private static String getImgUrl(Integer offerId){
        OfferImg offerImg = OfferImg.dao.findFirst("select * from offer_img where offer_spec_id = ?",offerId);
        return offerImg.getUrl();
    }
}
